import { Button, Form, Input, Modal, Space } from "antd";
import { useRef, useState } from "react";
import AdvanceTree, { AdvanceTreeNode } from "./AdvanceTree";
import { menuList } from "./menu";

const Home: React.FC = function () {
  const treeRef = useRef<any>();
  const formRef = useRef<any>();
  const [showModal, setShowModal] = useState(false);
  const [temp, setTemp] = useState<AdvanceTreeNode>();
  const data = menuList.map((t) => ({
    ...t,
    title: `${t.name}【${t.path}】`,
    key: t.uuid ? t.uuid : t.id,
  }));

  return (
    <div style={{ paddingTop: 50, textAlign: "left" }}>
      <Button
        onClick={() => {
          console.log(treeRef.current.getData());
        }}
      >
        获取数据
      </Button>
      <AdvanceTree
        ref={treeRef}
        data={data}
        onOpenAddModal={(pid) => {
          setTemp({ pid, key: -1, title: "", children: [] });
          setShowModal(true);
        }}
        onOpenModifyModal={(node) => {
          setTemp({ ...node });
          setShowModal(true);
        }}
      />
      <Modal title="菜单信息" visible={showModal} footer={null} destroyOnClose>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 22 }}
          initialValues={temp}
          ref={formRef}
          onFinish={(values: any) => {
            if (temp?.key !== -1) {
              treeRef.current?.updateNode({ ...temp, ...values });
            } else {
              treeRef.current?.addNode(
                { ...temp, ...values, key: Math.random(), children: [] },
                temp?.pid
              );
            }
            setShowModal(false);
          }}
        >
          <Form.Item name="title" label="Name">
            <Input />
          </Form.Item>
          <Form.Item name="path" label="Path">
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 22 }}>
            <Space>
              <Button
                onClick={() => {
                  setShowModal(false);
                }}
              >
                Cancel
              </Button>
              <Button type="primary" htmlType="submit">
                Submit
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

Home.displayName = "Home";
export default Home;
